package com.dao.impl;

import com.core.model.user.Administrator;
import com.core.model.user.Customer;
import com.core.model.user.User;
import com.core.model.user.UserRole;
import com.dao.UserDao;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-10-23
 * Time: 下午2:57
 * To change this template use File | Settings | File Templates.
 */
@Repository("userDao")
public class UserDaoImpl extends EntityDaoImpl implements UserDao {


    @Override
    public Customer findCustomerByUsername(String username) {
        String hql = "from " + Customer.class.getName() + " u where u.username = :username";
        Query query = currentSession().createQuery(hql);
        query.setParameter("username", username);
        List<Customer> list = query.list();
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Administrator findAdministratorByUsername(String username) {
        String hql = "from " + Administrator.class.getName() + " u where u.username = :username";
        Query query = currentSession().createQuery(hql);
        query.setParameter("username", username);
        List<Administrator> list = query.list();
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public void delUserRoleByUserId(User user) {
        String hql = "delete from " + UserRole.class.getName() + " a where a.user=:user";
        Query query = currentSession().createQuery(hql);
        query.setParameter("user", user);
        query.executeUpdate();
    }

}
